import logging
import time

import jwt
from django.conf import settings
from django.http import HttpRequest

from common.errors import AuthFailure
from user_center.models import User

logger = logging.getLogger(__name__)


def login_required(view_func):
    def wrapper(request: HttpRequest) -> User:
        jwt_secret = settings.SECRET_KEY
        jwt_token = request.headers.get("token")
        if not jwt_token:
            logger.warning("jwt token not found")
            raise AuthFailure()
        try:
            claims = jwt.decode(jwt_token, jwt_secret, algorithms=["HS256"])
        except jwt.PyJWTError as e:
            logger.warning(dict(token=jwt_token, e=e))
            raise AuthFailure()
        if claims.get("exp") < time.time():
            raise AuthFailure("登录已过期，请重新登录！")

        data = claims.get("data")
        if not data:
            logger.warning("token中没有data信息")
            raise AuthFailure()
        user = User(
            id=data["user_id"],
            username=data["username"],
            email=data["email"],
        )
        if user:
            request.user = user
            return view_func(request)
        raise AuthFailure()

    return wrapper
